package com.hutu.tree;

/**
 * 704. 二分查找 https://leetcode-cn.com/problems/binary-search/
 *
 * @author hutu
 * @date 2020/12/17 9:54 上午
 */
public class BinarySearch {

    public static int binarySearch(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(binarySearch(new int[]{1,2,3,4,7},8));
    }

}
